package apptoko.com.network;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.Log;
import apptoko.com.adapter.NotificationHelper;
import apptoko.com.util.Utils;

import apptoko.com.R;
;

public class InstallBackgroundTask extends AsyncTask<String, Void, String> {
	
	private NotificationHelper notification;
	private InstallBackgroundCallback callback;
	private int notificationId;
	private String title;
	private Context context;
	private String path = "";
	
	public InstallBackgroundTask(Context context){
		this.context = context;
	}
	
	public void setInstallBackgroundCallback(InstallBackgroundCallback callback){
		this.callback = callback;
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		notification = new NotificationHelper(context);
	}

	@Override
	protected String doInBackground(String... params) {
		notificationId = params[0].length();
		title = params[1];
		Intent notifyIntent = new Intent();
	    PendingIntent pending = PendingIntent.getActivity(context, 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
		notification.createNotification(notificationId, title, context.getResources().getString(R.string.installing), context.getResources().getString(R.string.installing)  + " " + title, pending);
		Process installProcess;
		String line;
		String result = "";
		try {
			installProcess = Runtime.getRuntime().exec("su");
			DataOutputStream os = new DataOutputStream(installProcess.getOutputStream());
			path = Utils.normalizationFileName(params[0]);
			Log.e(title, path);
			os.writeBytes("pm install -r " + path + "\n");
			os.writeBytes("exit\n");
			os.flush();
			DataInputStream dis = new DataInputStream(installProcess.getInputStream());
            while((line = dis.readLine()) != null) {
                result += line;
            }
            installProcess.waitFor();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return result;
	}

	@Override
	protected void onPostExecute(String result) {
		super.onPostExecute(result);
		if(result.equalsIgnoreCase("success") && !TextUtils.isEmpty(result)){
			notification.cancel(notificationId);
			if(callback != null){
				callback.onInstallSuccess();
			}
		} else {
			Intent notifyIntent = new Intent();
		    PendingIntent pending = PendingIntent.getActivity(context, 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
			notification.complete(notificationId, null, title, context.getResources().getString(R.string.install_fail) + " " + result, context.getResources().getString(R.string.install_fail) + " " + result, pending);
			if(callback != null){
				callback.onIOExeption();
			}
		}
	}
}
